package com.woniu.cq.springboot_mybatisplus_shiro.conf;

import com.woniu.cq.springboot_mybatisplus_shiro.dao.AuthMapper;
import com.woniu.cq.springboot_mybatisplus_shiro.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @Author: Klaus
 * @Date: 2020/9/2 20:13
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private AuthMapper authMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        //获取该用户对应的角色
        Set<String> rolesSet = authMapper.findRolesById(user.getUserId());
        //获取该用户对应的权限
        Set<String> pres = authMapper.findPreById(user.getUserId());
        System.out.println("该用户所拥有权限"+pres.size());
        System.out.println("该用户所拥有权限"+rolesSet.size());
        for (String pre : pres) {
            System.out.println(pre);
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //设置该用户对应的角色
        simpleAuthorizationInfo.setRoles(rolesSet);
        //设置该用户对应的权限
        simpleAuthorizationInfo.setStringPermissions(pres);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("进入验证：{}",token.getPrincipal());
        User user = authMapper.findUserByAccount((String)token.getPrincipal());
        if(user==null){
            throw new UnknownAccountException("账户不存在");
        }
        return new SimpleAuthenticationInfo(user,user.getUserPassword(),getName());
    }
}
